# -*- coding: utf-8 -*-
"""
乒乓球培训管理系统 - 评价模型
管理课程的双向评价系统
"""

from datetime import datetime
from flask_sqlalchemy import SQLAlchemy

from app import db


class Evaluation(db.Model):
    """
    评价模型
    管理课程结束后的双向评价
    """
    __tablename__ = 'evaluations'

    # 基础字段
    id = db.Column(db.BigInteger, primary_key=True, autoincrement=True)
    reservation_id = db.Column(db.BigInteger, db.ForeignKey('reservations.id'),
                              unique=True, nullable=False, comment='预约ID')
    student_id = db.Column(db.BigInteger, db.ForeignKey('users.id'),
                          nullable=False, comment='学员ID')
    coach_id = db.Column(db.BigInteger, db.ForeignKey('users.id'),
                        nullable=False, comment='教练ID')

    # 学员评价
    student_rating = db.Column(db.SmallInteger, nullable=True, comment='学员评分（1-5）')
    student_comment = db.Column(db.Text, nullable=True, comment='学员评价内容')
    student_submitted_at = db.Column(db.DateTime, nullable=True, comment='学员提交时间')

    # 教练评价
    coach_rating = db.Column(db.SmallInteger, nullable=True, comment='教练评分（1-5）')
    coach_comment = db.Column(db.Text, nullable=True, comment='教练评价内容')
    coach_submitted_at = db.Column(db.DateTime, nullable=True, comment='教练提交时间')

    # 审计字段
    created_at = db.Column(db.DateTime, nullable=False, default=datetime.now, comment='创建时间')

    # 关联关系
    student = db.relationship('User', foreign_keys=[student_id], backref='student_evaluations')
    coach = db.relationship('User', foreign_keys=[coach_id], backref='coach_evaluations')

    def __init__(self, **kwargs):
        super(Evaluation, self).__init__(**kwargs)

    def submit_student_evaluation(self, rating, comment=None):
        """提交学员评价"""
        if not (1 <= rating <= 5):
            return False, "评分必须在1-5之间"

        self.student_rating = rating
        self.student_comment = comment
        self.student_submitted_at = datetime.now()
        return True, "评价提交成功"

    def submit_coach_evaluation(self, rating, comment=None):
        """提交教练评价"""
        if not (1 <= rating <= 5):
            return False, "评分必须在1-5之间"

        self.coach_rating = rating
        self.coach_comment = comment
        self.coach_submitted_at = datetime.now()
        return True, "评价提交成功"

    def has_student_evaluation(self):
        """是否有学员评价"""
        return self.student_rating is not None

    def has_coach_evaluation(self):
        """是否有教练评价"""
        return self.coach_rating is not None

    def is_completed(self):
        """评价是否完成（双方都已评价）"""
        return self.has_student_evaluation() and self.has_coach_evaluation()

    def can_student_evaluate(self):
        """学员是否可以评价"""
        return not self.has_student_evaluation()

    def can_coach_evaluate(self):
        """教练是否可以评价"""
        return not self.has_coach_evaluation()

    def get_student_rating_stars(self):
        """获取学员评分星级显示"""
        if self.student_rating:
            return '★' * self.student_rating + '☆' * (5 - self.student_rating)
        return '未评价'

    def get_coach_rating_stars(self):
        """获取教练评分星级显示"""
        if self.coach_rating:
            return '★' * self.coach_rating + '☆' * (5 - self.coach_rating)
        return '未评价'

    @staticmethod
    def get_or_create_evaluation(reservation_id, student_id, coach_id):
        """获取或创建评价记录"""
        evaluation = Evaluation.query.filter_by(reservation_id=reservation_id).first()
        if not evaluation:
            evaluation = Evaluation(
                reservation_id=reservation_id,
                student_id=student_id,
                coach_id=coach_id
            )
            db.session.add(evaluation)
        return evaluation

    @staticmethod
    def get_coach_average_rating(coach_id):
        """获取教练平均评分"""
        result = db.session.query(db.func.avg(Evaluation.student_rating)).filter(
            Evaluation.coach_id == coach_id,
            Evaluation.student_rating.isnot(None)
        ).scalar()
        return float(result) if result else 0.0

    @staticmethod
    def get_coach_evaluation_count(coach_id):
        """获取教练评价数量"""
        return Evaluation.query.filter(
            Evaluation.coach_id == coach_id,
            Evaluation.student_rating.isnot(None)
        ).count()

    @staticmethod
    def get_student_evaluations(student_id, limit=None):
        """获取学员的评价记录"""
        query = Evaluation.query.filter_by(student_id=student_id).order_by(
            Evaluation.created_at.desc()
        )
        if limit:
            query = query.limit(limit)
        return query.all()

    @staticmethod
    def get_coach_evaluations(coach_id, limit=None):
        """获取教练的评价记录"""
        query = Evaluation.query.filter_by(coach_id=coach_id).order_by(
            Evaluation.created_at.desc()
        )
        if limit:
            query = query.limit(limit)
        return query.all()

    def to_dict(self):
        """转换为字典格式"""
        return {
            'id': self.id,
            'reservation_id': self.reservation_id,
            'student_id': self.student_id,
            'coach_id': self.coach_id,
            'student_rating': self.student_rating,
            'student_comment': self.student_comment,
            'student_submitted_at': self.student_submitted_at.isoformat() if self.student_submitted_at else None,
            'coach_rating': self.coach_rating,
            'coach_comment': self.coach_comment,
            'coach_submitted_at': self.coach_submitted_at.isoformat() if self.coach_submitted_at else None,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'student_name': self.student.real_name if self.student else None,
            'coach_name': self.coach.real_name if self.coach else None,
            'is_completed': self.is_completed(),
            'student_rating_stars': self.get_student_rating_stars(),
            'coach_rating_stars': self.get_coach_rating_stars()
        }

    def __repr__(self):
        return f'<Evaluation reservation_id={self.reservation_id} student={self.student_id} coach={self.coach_id}>'